Imports Wrox.Commerce

Partial Class ShoppingCartControl
    Inherits System.Web.UI.UserControl

    Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        If Profile.Cart Is Nothing Then
            Return
        End If

        If Not Page.IsPostBack Then
            BindGrid()
        End If

        If Profile.Cart.Items.Count = 0 Then
            TotalLabel.Visible = False
            DiscountPanel.Visible = False
        End If

    End Sub

    Private Sub BindGrid()

        ' bind to the items in the cart
        CartGrid.DataSource = Profile.Cart.Items
        DataBind()


        ' TODO: sort out alignment
        If Context.User.IsInRole("FanClubMember") Then
            SubTotalLabel.Text = String.Format("Sub-Total:{0,35:C}", Profile.Cart.SubTotal)
            MemberDiscount.Text = String.Format("Member Discount:{0:C}", Profile.Cart.MemberDiscount)
            DiscountPanel.Visible = True
        End If

        TotalLabel.Text = String.Format("Total:{0,19:C}", Profile.Cart.Total)

    End Sub

    Sub CartGrid_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs)

        CartGrid.EditIndex = e.NewEditIndex
        BindGrid()

    End Sub

    Sub CartGrid_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs)

        Dim QuantityTextBox As TextBox = CType(CartGrid.Rows(e.RowIndex).Cells(2).Controls(0), TextBox)
        Dim Quantity As Integer = Convert.ToInt32(QuantityTextBox.Text)

        If Quantity = 0 Then
            Profile.Cart.Items.RemoveAt(e.RowIndex)
        Else
            Profile.Cart.Items(e.RowIndex).Quantity = Quantity
        End If

        CartGrid.EditIndex = -1
        BindGrid()

    End Sub

    Sub CartGrid_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs)

        CartGrid.EditIndex = -1
        BindGrid()

    End Sub

    Sub CartGrid_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs)

        Profile.Cart.Items.RemoveAt(e.RowIndex)
        BindGrid()

    End Sub

End Class
